package ppjava12v1.chess.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ppjava12v1.chess.Exceptions.IncorrectPositionException;
import ppjava12v1.chess.dao.UserDAO;
import ppjava12v1.chess.entities.games.Coordinate;
import ppjava12v1.chess.entities.games.Game;
import ppjava12v1.chess.entities.users.User;
import ppjava12v1.chess.enums.Role;
import ppjava12v1.chess.hash.HashCode;
import ppjava12v1.chess.service.GameService;
import ppjava12v1.chess.service.Move2Service;

import java.util.ArrayList;

@Controller
public class LoginController {


    @Autowired
    UserDAO userDAO;

    @Autowired
    HashCode hashCode;



    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getLogin() {
        return "forward:/login";
    }

    @RequestMapping("registerform")
    public ModelAndView registrationForm(@ModelAttribute User user) {
        return new ModelAndView("register", "user", user);
    }

    @RequestMapping("register")
    public ModelAndView registerUser(@ModelAttribute User user,
                                     @RequestParam(required = false) String realName,
                                     @RequestParam(required = false) String nickName) {
        String hashPassword = hashCode.getHashPassword(user.getPassword());

        String message = "";

        user.setPassword(hashPassword);

        user.add(Role.ROLE_USER);

        user.add(Role.ROLE_ADMIN);

        user.setActive(true);

        user.getProfile().setNickName(nickName);

        user.getProfile().setRealName(realName);

        message = userDAO.saveUser(user);

        if (message.equals("Success")) {

            return new ModelAndView("login", "user", user);

        } else {

            return new ModelAndView("register", "message", message);

        }

    }

    @RequestMapping("profile")
    public ModelAndView profile(@ModelAttribute User user) {

        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String login = authentication.getName();
        user = userDAO.getByLogin(login);

        return new ModelAndView("profile", "name", user.toString());
    }

    @RequestMapping("login")
    public ModelAndView getLoginForm(
            @RequestParam(required = false) String authfailed, String logout,
            String denied) {
        String message = "";
        if (authfailed != null) {
            message = "Invalid login or password!";
        } else if (logout != null) {
            message = "Logged Out successfully!";
        } else if (denied != null) {
            message = "Access denied for this user!";
        }
        return new ModelAndView("login", "message", message);
    }

    @RequestMapping("user")
    public ModelAndView geUserPage() {

        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String login = authentication.getName();
        User user = userDAO.getByLogin(login);

        return new ModelAndView("move", "user", user);

    }

    @RequestMapping("admin")
    public String geAdminPage() {
        return "admin";
    }

    @RequestMapping("403page")
    public String ge403denied() {
        return "redirect:login?denied";
    }

    @RequestMapping("move")
    public ModelAndView getMove(@RequestParam int row,
                                @RequestParam int col,
                                @RequestParam(required = false) int side,
                                @RequestParam(required = false) String figure ) throws IncorrectPositionException {

        // для показания работоспособности передается цвет и сама фигура, в рабочей программе фигура и цвет должна подтягиватся
        // с базы по координатам

        // например figure = dao.getFigure (new Coordinate(row, col)));

        ArrayList<Coordinate> coordinateList = new ArrayList<Coordinate>();
     //   coordinateList.addAll(new MoveService().figureMove(FigureType.valueOf(figure), side, new Coordinate(row, colom)));
        Game newGame = new Game();
        GameService gameService = new  GameService();
        gameService.startGame(newGame);

        coordinateList.addAll(new Move2Service().figureMove(newGame.getDesk(), new Coordinate(row, col)));

        return new ModelAndView("move", "coordinateList", coordinateList);
    }

}
